<?php
// Receives in-world data from objects and stores on database

// Main starts here

if (isset($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY']))
{
	require_once($_SERVER['DOCUMENT_ROOT'] . "/config.php");
	include(ABS_PATH . "misc/functions.php");
	
	try {
		$db = new PDO(PDO_PREFIX . SQLITE_DB_FILENAME);
	}	
	catch(PDOException $e)
	{
		header("HTTP/1.0 503 Service Unavailable");
   		printf("Connect failed: %s\n", $e->getMessage());
   		_log(__FILE__ . " - line " . __LINE__ . ": Error connecting to database: " . $e->getMessage());
    	exit();
	}
	
	// To-do: need to check for phantom; this is not an 'obstacle' even if it might feature on the
	//  database (what for?)
	
	try {
		$db->exec("REPLACE INTO Obstacles (`UUID`, `Name`, `BotKey`, `BotName`, `Type`, `Origin`, `Position`, `Rotation`, `Velocity`, `Phantom`, `Prims`, `BBHi`, `BBLo`, `LastUpdate`) VALUES ('" .
			$_REQUEST['key'] . "','" .											// key of obstacle seen
			addslashes($_REQUEST['name']) . "','" .								// name of obstacle seen
			$_SERVER['HTTP_X_SECONDLIFE_OWNER_KEY'] . "','" .					// key and name of 'bot doing
			addslashes($_SERVER['HTTP_X_SECONDLIFE_OWNER_NAME']) . "','" .		//  the update
			$_REQUEST['type'] . "','" .											// AGENT, SCRIPTED, etc. as bitflags
			$_REQUEST['origin'] . "','" .										// castray or sensor
			trim($_REQUEST['pos'], "<>()") . "','" .								// Vector with position, rotation, velocity
			trim($_REQUEST['rot'], "<>()") . "','" .
			trim($_REQUEST['vel'], "<>()") . "','" .
			$_REQUEST['phantom'] . "','" .
			$_REQUEST['prims'] . "','" .
			trim($_REQUEST['bbhi'], "<>()") . "','" . // bounding box vector 0
			trim($_REQUEST['bblo'], "<>()") . "','" . // and 1
			$_REQUEST['timestamp'] . "')");
	}	
	catch(PDOException $e)
	{
		header("HTTP/1.0 503 Service Unavailable");
   		printf("REPLACE query failed: %s\n", $e->getMessage());
   		_log(__FILE__ . " - line " . __LINE__ . sprintf(": REPLACE query failed: %s\n", $e->getMessage())); 
    	exit();
	}
	

	header("HTTP/1.0 200 OK");
	header("Content-type: text/plain; charset=utf-8");

	$reply = $_SERVER['HTTP_X_SECONDLIFE_OWNER_NAME'] . " sent us:\n" .
		'Key: ' . $_REQUEST['key'] . ' Name: ' . $_REQUEST['name']. "\n" .
		'Position: ' . $_REQUEST['pos'] . ' Rotation: ' . $_REQUEST['rot'] . "\n" .
		'Type: ' . $_REQUEST['type'] . "\n" . 'Origin: ' . $_REQUEST['origin'] . "\n" .
		'Velocity: ' . $_REQUEST['vel'] . 
		' Phantom: ' . $_REQUEST['phantom'] . 
		' Prims: ' . $_REQUEST['prims'] . "\n" .
		'BB high: ' . $_REQUEST['bbhi'] . 
		' BB low: ' . $_REQUEST['bblo'] . "\n" .
		'Timestamp: ' . $_REQUEST['timestamp'];
	echo $reply;
	// _log(__FILE__ . " [Received Sensor Data] - " .$reply);
}
else
{
	header("HTTP/1.0 405 Method Not Allowed");
	echo "Not called from within the virtual world.";
}
?>